<!-- 面试记录 -->
<template>
  <div class="interview-record-container">
    <div class="header">
      <h2>模拟面试记录</h2>
      <div class="actions">
        <a-button type="primary" @click="startMockInterview">
          <template #icon>
            <plus-outlined />
          </template>
          开始模拟
        </a-button>
      </div>
    </div>

    <a-card class="record-card">
      <a-table
        :columns="columns"
        :data-source="interviewRecords"
        :pagination="pagination"
        row-key="id"
        :loading="loading"
        bordered
      >
        <!-- 自定义status表格列 -->
        <template #status="{ text }">
          <a-tag :color="getStatusColor(text)">
            {{ getStatusText(text) }}
          </a-tag>
        </template>

        <!-- 自定义时长列 -->
        <template #duration="{ text }">
          <span>{{ formatDuration(text) }}</span>
        </template>

        <!-- 自定义时间列 -->
        <template #time="{ text }">
          <span>{{ formatDate(text) }}</span>
        </template>

        <!-- 自定义action列 -->
        <template #action="{ record }">
          <a-button
            type="link"
            @click="viewReport(record)"
            :disabled="record.interviewStatus !== 2"
          >
            查看报告
          </a-button>
          <a-popconfirm
            title="确定要删除此笔试记录吗？"
            ok-text="确定"
            cancel-text="取消"
            @confirm="deleteRecord(record)"
          >
            <a-button type="link" danger>删除</a-button>
          </a-popconfirm>
        </template>
      </a-table>
    </a-card>

    <!-- 无数据时的提示 -->
    <a-empty v-if="interviewRecords.length === 0 && !loading" description="暂无面试记录" />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import {
  Card as ACard,
  Table as ATable,
  Button as AButton,
  Tag as ATag,
  message,
  Empty as AEmpty,
} from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { useRouter } from 'vue-router'
import {
  deleteTecInterviewUsingGet,
  getTecInterviewListUsingGet,
} from '@/api/tecInterviewController'
import { formatDuration } from '@/utils/FormatTime'

const router = useRouter()
const loading = ref(true)

// 表格列定义
const columns = [
  {
    title: '岗位',
    dataIndex: 'position',
    key: 'position',
    width: 150,
    sorter: (a, b) => a.position.localeCompare(b.position),
  },
  {
    title: '公司',
    dataIndex: 'company',
    key: 'company',
    width: 150,
    sorter: (a, b) => a.company.localeCompare(b.company),
  },
  {
    title: '技术领域',
    dataIndex: 'techField',
    key: 'techField',
    width: 120,
  },
  {
    title: '面试时间',
    dataIndex: 'createTime',
    key: 'time',
    width: 160,
    slots: { customRender: 'time' },
    sorter: (a, b) => new Date(a.createTime) - new Date(b.createTime),
  },
  {
    title: '时长',
    dataIndex: 'interviewDuration',
    key: 'duration',
    width: 100,
    align: 'center',
    slots: { customRender: 'duration' },
    sorter: (a, b) => a.interviewDuration - b.interviewDuration,
  },
  {
    title: '状态',
    dataIndex: 'interviewStatus',
    key: 'status',
    width: 120,
    align: 'center',
    slots: { customRender: 'status' },
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    align: 'center',
    slots: { customRender: 'action' },
  },
]

// 面试记录数据
const interviewRecords = ref([])

// 分页配置
const pagination = ref({
  pageSize: 10,
  showSizeChanger: true,
  pageSizeOptions: ['5', '10', '20', '50'],
  showTotal: (total) => `共 ${total} 条记录`,
})

/**
 * 获取状态标签颜色
 * @param {number} status 面试状态码
 * @returns {string} 颜色代码
 */
const getStatusColor = (status) => {
  const map = {
    0: 'orange', // 未完成
    1: 'blue', // 分析中
    2: 'green', // 已完成
  }
  return map[status] || 'gray'
}

/**
 * 获取状态文本
 * @param {number} status 面试状态码
 * @returns {string} 状态文本
 */
const getStatusText = (status) => {
  const map = {
    0: '未完成',
    1: '分析中',
    2: '已完成',
  }
  return map[status] || '未知状态'
}

/**
 * 格式化日期
 * @param {string} dateString ISO日期字符串
 * @returns {string} 格式化后的日期字符串
 */
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date
    .getDate()
    .toString()
    .padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date
    .getMinutes()
    .toString()
    .padStart(2, '0')}`
}

/**
 * 开始模拟面试
 */
const startMockInterview = () => {
  router.push('/api/tec/interview')
}

/**
 * 查看面试报告
 * @param {Object} record 面试记录
 */
const viewReport = (record) => {
  if (record.interviewStatus !== 2) {
    message.warning('面试报告正在分析中，请稍后查看')
    return
  }

  message.success(`正在查看 ${record.position} 的面试报告`)
  router.push(`/api/tec/analyze?id=${record.id}`)
}

/**
 * 删除面试记录
 * @param {Object} record 面试记录
 */
const deleteRecord = async (record) => {
  const res = await deleteTecInterviewUsingGet({ tecInterviewId: record.id })
  if (res.code === 0) {
    message.success('删除面试记录成功')
    // 重新加载数据
    await fetchInterviewRecords()
  } else {
    message.error('删除面试记录失败：' + (res.message || '未知错误'))
  }
}

/**
 * 获取面试记录列表
 */
const fetchInterviewRecords = async () => {
  loading.value = true
  try {
    const response = await getTecInterviewListUsingGet()
    if (response.code === 0 && response.data) {
      interviewRecords.value = response.data
    } else {
      message.error('获取面试记录失败：' + (response.message || '未知错误'))
    }
  } catch (error) {
    console.error('获取面试记录出错：', error)
    message.error('获取面试记录失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchInterviewRecords()
})
</script>

<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.header h2 {
  font-size: 24px;
  color: #2c3e50;
  margin: 0;
}

.record-card {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.interview-record-container {
  padding-top: 50px;
  min-height: 500px;
}

/* 表格样式 */
:deep(.ant-table) {
  border-radius: 8px;
}

:deep(.ant-table-thead > tr > th) {
  background-color: #f0f2f5;
  font-weight: 600;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background-color: #e6f7ff !important;
}

:deep(.ant-btn-link[disabled]) {
  color: rgba(0, 0, 0, 0.25);
  cursor: not-allowed;
}

:deep(.ant-table-row) {
  transition: all 0.3s;
}
</style>
